package com.copa.l57;

import java.util.*;

/**
 * @author copa
 * @createDate 2022-05-13 16:53
 * @function 排序法 解法跟l56差不多
 */
public class Test1 {
    /**
     * 这里我觉得解法跟l56类似，就是多了一步，插入新的数组，下面的套路基本都跟l56一样...但是我还真没想到...想复杂了...怪我脑子没反应过来...
     * @param intervals
     * @param newInterval
     * @return
     */
    public int[][] insert(int[][] intervals, int[] newInterval) {
        // 用这个会报java.lang.UnsupportedOperationException
        // List<int[]> intervalList = Arrays.asList(intervals);
        List<int[]> intervalList = new ArrayList<>(Arrays.asList(intervals));
        // 插入newInterval，就这一步跟l56不同而已
        intervalList.add(newInterval);
        // 下面开始跟l56一样了
        Collections.sort(intervalList, (a, b) -> a[0] - b[0]);
        List<int[]> result = new ArrayList<>();
        for (int i = 0; i < intervalList.size(); i++) {
            if (result.size() == 0 || result.get(result.size() - 1)[1] < intervalList.get(i)[0]) {
                result.add(intervalList.get(i));
            } else {
                result.get(result.size() - 1)[1] = Math.max(result.get(result.size() - 1)[1], intervalList.get(i)[1]);
            }
        }
        return result.toArray(new int[result.size()][2]);
    }

    public static void main(String[] args) {
        int[][] intervals = new int[][]{{1,2},{3,5},{6,7},{8,10},{12,16}};
        //int[][] intervals = new int[][]{{0,5},{9,12}};
        int[] newInterval = new int[]{4,8};
        for (int[] result : new Test1().insert(intervals, newInterval)) {
            System.out.print(Arrays.toString(result) + "\t");
        }
    }
}
